<template>
  <gui-page ref="guiPage" :customHeader="true">
    <!-- 导航 -->
    <template v-slot:gHeader>
      <nav-bar-custom left-icon="left" :leftType="'1'" :title="$t('newTranslation.finishedProductAdditional')"
        :rightText="$t('distributedEnter.scanRecord')" @clickRight="clickRight"
        @clickLeftBack="clickLeftBack"></nav-bar-custom>
    </template>

    <template v-slot:gBody>
      <view class="barcodeSplitting">
        <!-- 扫描条码部分 -->
        <view class="gui-bg-white gui-dark-bg-level-3 gui-padding-x distributed-head">
          <view class="custom-card-title">
            <text class="title-line"></text>
            {{ $t('Common.scanningInfo') }}
          </view>
          <view class="gui-form-item gui-border-b" style="padding: 20rpx 0;">
            <text class="item-info-title" style="padding-right: 40rpx;">
              <text class="required-color">*</text>
              {{ $t('distributedEnter.barcodeScan') }}
            </text>
            <uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.barCodes" type="search"
              :placeholder="$t('Common.scanningBarCode')" @confirm="confirm" @iconClick="iconClick">
            </uni-easyinput>
          </view>
        </view>

        <!-- 提示信息 -->
        <view class="gui-flex gui-rows gui-nowrap gui-align-items-center gui-margin-top">
          <view class="gui-title-line"></view>
          <text class="gui-primary-text gui-h6" style="padding-left:50rpx; padding-right:50rpx;">{{
            $t('hardwareOut.barcodeInformation')
          }}
          </text>
          <view class="gui-title-line"></view>
        </view>

        <!-- 条码展示部分 -->
        <scroll-view :show-scrollbar="false" :scroll-y="true" class="scroll">
          <view style="height: 15rpx"></view>
          <view class="card-boxCustom" v-if="data.cardShow">
            <view class="card-body">
              <view class="custom-card-title">
                <text class="title-line"></text>{{ $t('distributedOut.atPresent') }}
              </view>
              <view class="custom-card-itemOne">
                <text class="item-info-title">{{ $t('distributedOut.barcode') }}：</text>{{ data.scanInfo.barcode }}
              </view>
              <view class="custom-card-itemOne">
                <text class="body-item-title">{{ $t('multilingual.productionLine') }}：</text>{{ data.scanInfo.productionLine }}
              </view>
              <view class="custom-card-itemOne">
                <text class="body-item-title">{{ $t('distributedEnter.materialCode') }}：</text> {{ data.scanInfo.materialCode }}
              </view>
              <view class="custom-card-itemOne">
                <text class="body-item-title">{{ $t('distributedEnter.materialName') }}：</text>{{ data.scanInfo.materialName }}
              </view>
              <view class="custom-card-itemOne">
                <text class="body-item-title">{{ $t('distributedEnter.materialSpec') }}：</text>{{ data.scanInfo.specification }}
              </view>
              <view class="custom-card-itemOne">
                <view class="card-item-50">
                  <text class="item-info-title">{{ $t('distributedEnter.uom') }}：</text>{{ data.scanInfo.unit }}</view>
                <view class="card-item-50">
                  <text class="item-info-title">{{ $t('distributedEnter.qty') }}：</text>{{ data.scanInfo.qty }}
                </view>
              </view>
              <view class="custom-card-itemOne">
                <view class="card-item-50">
                  <text class="item-info-title">{{ $t('distributedOut.warehouse') }}：</text>{{ data.scanInfo.warehouse}}
                </view>
                <view class="card-item-50">
                  <text class="item-info-title">{{ $t('translationImage.process') }}：</text>{{ data.scanInfo.process }}
                </view>
              </view>
              <view class="custom-card-itemOne">
                <text class="item-info-title">{{ $t('distributedOut.location') }}：</text>{{ data.scanInfo.location }}
              </view>
            </view>
          </view>
        </scroll-view>

        <!-- 底部确定按钮 -->
        <view class="page-bottom-box bottom-postion">
          <view class="page-bottomBtn bottomBtn-bgcolor-green" @click="submit">{{ $t('calendar.submit') }}</view>
        </view>

        <!-- 普通弹窗 -->
        <uni-popup ref="popup" type="center">
          <view class="input-dialog-box" style="height:900rpx">
            <view class="input-dialog-content" style="margin-bottom: 280rpx;">
              <view class="custom-card-itemTwo" style="padding: 20rpx 0;">
                <text class="item-info-title" style="width:400rpx">
                  <text class="required-color">*</text>
                  {{ $t('newTranslation.productionLine') }}：
                </text>
                <comboGrid requestUrl="/wms/wmsBarcode/finishedRecord" v-model="data.productionLine"
                  :requestParam="data.positionParam" inputKey="production_line_code"
                  :placeholder="$t('distributedEnter.placeholderTextChoose')"
                  :gridPlaceholder="$t('Common.searchKeyWord')" :column="data.columnPointPosition.column"
                  bindValue="production_line_code" @setClick="getPointPositionClick">
                </comboGrid>
              </view>
              <view class="custom-card-itemTwo" style="padding: 20rpx 0;">
                <text class="item-info-title" style="width:400rpx">
                  <text class="required-color">*</text>
                  {{ $t('newTranslation.fgmaterialCode') }}：
                </text>
                <comboGrid requestUrl="/wms/basMaterial/getFinishedProduct" v-model="data.fgmaterialCode"
                  :requestParam="data.materialParam" inputKey="materialCode"
                  :placeholder="$t('distributedEnter.placeholderTextChoose')"
                  :gridPlaceholder="$t('Common.searchKeyWord')" :column="data.columnMaterial.column"
                  bindValue="materialCode" @setClick="getMaterialClick">
                </comboGrid>
              </view>
              <view class="gui-form-item gui-border-b" style="padding: 20rpx 0;">
                <text class="item-info-title" style="padding-right: 40rpx;">
                  <text class="required-color">*</text>
                  {{ $t('distributedEnter.qty') }}
                </text>
                <uni-easyinput class="uni-mt-5" v-model="data.quantity" type="number"></uni-easyinput>
                <text>{{ data.unit }}</text>
              </view>
              <!-- 添加年月日  -->
              <view class="title"></view>
              <view class="title-with-text">
                <text>{{ $t('equipmentRepair.Batch') }}</text>
              </view>
              <view class="custom-card-itemTwo" style="padding: 0 0 10rpx 0;text-align: left;display: flex;">
                <text class="item-info-title">{{ $t('equipmentRepair.day') }}：</text>
                <superweiCombox style="text-align: right;padding: 4rpx 0 !important;" :candidates="data.dayList"
                  :placeholder="$t('distributedOut.placeholder')" :isJSON="true" keyName="text" @select="selectDay"
                  v-model="data.selectedDay.day"></superweiCombox>
                <text class="item-info-title">{{ $t('equipmentRepair.month') }}：</text>
                <superweiCombox style="text-align: right;padding: 4rpx 0 !important;  " :candidates="data.monthList"
                  :placeholder="$t('distributedOut.placeholder')" :isJSON="true" keyName="text" @select="selectMonth"
                  v-model="data.selectedDay.month"></superweiCombox>
                <text class="item-info-title">{{ $t('equipmentRepair.year') }}：</text>
                <superweiCombox style="text-align: right;padding: 4rpx 0 !important;" :candidates="data.yearList"
                  :placeholder="$t('distributedOut.placeholder')" :isJSON="true" keyName="text" @select="selectYear"
                  v-model="data.selectedDay.year"></superweiCombox>
              </view>
              <view class="custom-card-itemTwo" style="padding: 20rpx 0;display: flex;justify-content: space-around;">
                <uni-easyinput class="uni-mt-5" :placeholder="$t('equipmentRepair.BatchRemarks')"
                  v-model="data.selectedDay.remarks"></uni-easyinput>
                <view class="continueInput" @click="continueInput">
                  {{ $t('equipmentRepair.continueInput') }}
                </view>
              </view>
            </view>
            <view class="input-dialog-footer" style="position: relative;top: -120rpx;left: 0;">
              <view class="input-dialog-button" @click="cancelFn">
                {{ $t('popup.cancel') }}
              </view>
              <view class="input-dialog-button dialog-button-left" @click="scanConfirmFn">
                {{ $t('popup.confirm') }}
              </view>
            </view>
          </view>
        </uni-popup>
      </view>
    </template>
  </gui-page>
</template>

<script setup>
//引入文件
import { navigate, navigateBack } from '@/utils/routerSkip.js'
import { ref, reactive, onMounted, computed, watch, toRaw } from 'vue'
import { getFinishedProduct, updateD, saveFinishedProduct, selectWmsBarcodeInfoForFPSupplement } from '@/api/api.js'
import pdaScan from '@/hooks/pdaScan.js'
import storageBin from '@/components/storageBin.vue'
import comboGrid from '@/components/comboGrid.vue'
import superweiCombox from '@/components/superweiCombox';
import { onBackPress, onLoad } from '@dcloudio/uni-app'
import { useStore } from 'vuex'
import { basPdaOperationLogFn } from '@/utils/index.js'
import { USERINFO, OPERATION_COMMIT, OPERATION_LOOK, OPERATION_SCAN } from '@/constant/index.js'

//JS国际化引入
import { useI18n } from 'vue-i18n'
//注册组件
components: { comboGrid, superweiCombox, storageBin }

const { t } = useI18n()
let store = useStore()
const { scan } = pdaScan()
// 弹框的属性
let popup = ref(null)

const data = reactive({
  barCodes: '',  // 条码
  barcodeList: [],// 扫描记录的存储
  productionLine: '',//产线
  productionLineName: '',//产线名
  fgmaterialCode: '',//成品代码
  scanInfo: {}, //当前扫描信息
  scanInfoItem: {}, //产线或者物料选择的数据存储
  unit: '', //单位
  columnPointPosition: { //产线的下拉里面显示字段
    column: [{
      label: t('newTranslation.productionLineName'), // 产出名称
      name: 'production_line_name',
    }, {
      label: t('newTranslation.productionLineCode'), // 产出编码
      name: 'production_line_code',
    }]
  },
  columnMaterial: { //物料的下拉里面显示字段
    column: [{
      label: t('distributedEnter.materialName'), // 物料名称
      name: 'materialName',
    }, {
      label: t('distributedEnter.materialCode'), // 物料编码
      name: 'materialCode',
    }]
  },
  positionParam: {
    production_line_code: ''
  },
  materialParam: {
    materialCode: ''
  },
  materialId: null, // 物料id
  lineId: null, // 产线id
  materialArry: [],
  quantity: null,
  urlCode: '',
  dayList: computed(() => {
    return Array.from({ length: 31 }, (_, i) => ({
      value: (i + 1).toString().padStart(2, '0'),
      text: (i + 1).toString().padStart(2, '0'),
    }));
  }),
  monthList: computed(() => {
    return Array.from({ length: 12 }, (_, i) => ({
      value: (i + 1).toString().padStart(2, '0'),
      text: t(`months.month${i + 1}`), // 国际化键名
    }));
  }),
  yearList: computed(() => {
    const startYear = new Date().getFullYear();
    const totalYears = 10;
    return Array.from({ length: totalYears }, (_, i) => {
      const year = startYear + i;
      return {
        value: year,
        text: year
      };
    });
  }),
  selectedDay: {
    year: '',
    day: '',
    month: '',
    remarks: ''
  },
  tableDayS: [],
})

onLoad((options) => {
  if (options && options.barcode) {
    getCode(options.barcode, 'pda')
    data.urlCode = options.barcode
  }

})

//
onMounted(() => {
  uni.$on('scancodedate', (data) => {
    console.log('获取到的code：' + data.code)
    getCode(data.code, 'pda')
  })
  material()
})

//时间 日 月  年 选择
const selectDay = (e) => {
  data.selectedDay.day = e.value
}
const selectMonth = (e) => {
  data.selectedDay.month = e.value
}
const selectYear = (e) => {
  data.selectedDay.year = e.value
}

// 继续输入
const continueInput = () => {
  if (data.selectedDay.year && data.selectedDay.day && data.selectedDay.month && data.selectedDay.remarks) {
    data.tableDayS.push(data.selectedDay)
    data.selectedDay = {
      year: '',
      day: '',
      month: '',
      remarks: ''
    }
  } else {
    uni.showToast({
      title: t('months.selectInput'),
      icon: 'none'
    })
    return
  }

}

// 获取成品料号
const material = () => {
  getFinishedProduct({
    page: 1, rows: 100
  }).then(res => {
    data.materialArry = res.data.rows
  })
}

// 存储扫描数据到vuex
data.barcodeList = computed(() => {
  return store.state.finishedProductAdditional
})

// 扫描条码事件
const confirm = () => {
  getCode(data.barCodes, 'keydown')
}

// 监听用户使用相机
const iconClick = async (type) => {
  if (type === 'suffix') {
    let code = await scan()
    getCode(code, 'scan')
  }
}

const getCode = (code, type) => {
  if (code.length <= 0) {
    uni.showToast({ title: t('newTranslation.correctly'), icon: 'none' })
    return
  }
  // 存储扫描的的条码,通过barode去判断是否有重复
  let arr = data.barcodeList.filter(x => x.barcode == code)

  if (arr.length > 0) {
    uni.showToast({ title: t('smashRemoval.codesRepeatedly'), icon: 'none' })
    return
  }
  data.barCodes = code
  let parmes = {
    barcode: code
  }
  uni.showLoading({
    title: 'loading',
    mask: true
  })
  selectWmsBarcodeInfoForFPSupplement(parmes).then(res => {
    uni.hideLoading()
    try {
      let inputParameter = '无'
      let returnParameter = JSON.stringify(data.barcodeList)
      let operationPicture = '成品补录'
      let callInterface = '无'
      let opertionParmes = {
        inputParameter,
        returnParameter,
        operationPicture,
        callInterface,
        responseCode: '无', //返回状态
        errorMessage: '无', //错误信息
        isPass: 'Y', //是否成功 Y N
        operationType: OPERATION_SCAN
      }
      basPdaOperationLogFn(opertionParmes)
    } catch (error) {
      console.log(error)
    }
    if (res.status == 200) {
      // 打开弹框
      popup.value.open()
      data.scanInfo = {}
      data.tableDayS = []
      data.selectedDay = {
        year: '',
        day: '',
        month: '',
        remarks: ''
      }
    } else {
      uni.showToast({ title: res.message, icon: 'none' })
    }
  })

}

// 选择
const getPointPositionClick = (x) => {
  data.lineId = x.process_id
  data.productionLine = x.production_line_code
  data.productionLineName = x.production_line_name
  data.fgmaterialCode = x.production_material_code
  data.positionParam.production_material_code = x.production_material_code
  data.quantity = x.qty
  //data.unit=x.unit
  data.unit = 'box'  //这里单位暂时写死box
  data.materialArry?.forEach(item => {

    if (item.materialCode == data.fgmaterialCode) {

      data.scanInfoItem = item
      //data.materialId=item.id
      //data.fgmaterialCode=item.materialCode
      //data.materialParam.materialCode = item.materialCode;
    }
  })

}

const getMaterialClick = (x) => {
  // console.log(x)
  data.materialId = x.id
  data.fgmaterialCode = x.materialCode
  data.scanInfoItem = x
  data.materialParam.materialCode = x.materialCode
}

// 弹框的确定按钮
const scanConfirmFn = () => {

  if (!data.fgmaterialCode) {
    uni.showToast({ title: t('JsInternational.plsInformation'), icon: 'none' })
    return
  }
  if (!data.productionLine) {
    uni.showToast({ title: t('JsInternational.chooseLine'), icon: 'none' })
    return
  }
  if (!data.quantity) {
    uni.showToast({ title: t('smashRemoval.pleaseEnterQty'), icon: 'none' })
    return
  }
  if (Number(data.quantity) <= 0) {
    uni.showToast({ title: t('smashRemoval.pleaseEnterQty'), icon: 'none' })
    return
  }
  // 如果没有点击继续输入 将输入的批次添加
  if (data.selectedDay.year && data.selectedDay.day && data.selectedDay.month && data.selectedDay.remarks) {
    data.tableDayS.push(data.selectedDay)
  } else {
    data.tableDayS = []
  }
  // 物料信息
  data.scanInfo = Object.assign({}, data.scanInfoItem)
  // 产线及其他
  data.scanInfo.productionLine = data.productionLine
  data.scanInfo.productionName = data.productionLineName
  data.scanInfo.lineId = data.lineId

  data.scanInfo.qty = data.quantity
  data.scanInfo.barcode = data.barCodes

  data.scanInfo.process = 'JJG'
  data.scanInfo.warehouse = 'JJG'
  data.scanInfo.location = 'DR001'

  // 批次的数据，可能是多个
  data.scanInfo.tableDayS = data.tableDayS

  // 数据存储到vuex
  store.commit('addFinishedProductAdditional', data.scanInfo)

  data.cardShow = true
  popup.value.close()

  data.barCodes = ' '

}

// 弹框的取消
const cancelFn = () => {
  popup.value.close()
  data.barCodes = ''

}

// 提交
const submit = () => {
  console.log(data.barcodeList)
  let arr1 = data.barcodeList.filter(x => (!x.materialCode))
  if (arr1.length) {
    return uni.showToast({
      title: t('taskList.withBlankMaterial'),
      icon: 'none'
    })
  }
  if (!data.barcodeList.length) {  //判断请扫描条码
    uni.showToast({
      title: t('stockManage.pleaseScanCode'),
      icon: 'none'
    })
    return
  }

  let parmes = []
  data.barcodeList.forEach(e => {
    var obj = {
      productionLineCode: e.productionLine,
      productionLineName: e.productionName,
      materialCode: e.materialCode,
      materialName: e.materialName,
      cartonNo: e.barcode,
      qty: e.qty
    }
    parmes.push(obj)

  })
  uni.showLoading({
    title: 'loading',
    mask: true
  })

  saveFinishedProduct(parmes).then((res) => {
    //隐藏加载框
    uni.hideLoading()
    try {
      let inputParameter = JSON.stringify(parmes)
      let returnParameter = JSON.stringify(res)
      let operationPicture = '成品补录'
      let callInterface = res.rquestUrl
      let opertionParmes = {
        inputParameter,
        returnParameter,
        operationPicture,
        callInterface,
        responseCode: res.status,//返回状态
        errorMessage: res.message,//错误信息
        isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
        operationType: OPERATION_COMMIT
      }
      basPdaOperationLogFn(opertionParmes)
    } catch (error) {
    }
    if (res.status == 200) {
      // 清空数据
      data.scanInfo = {}

      store.commit('clearFinishedProductStorage')
      uni.showToast({ title: t('smashRemoval.submitSuccessfully'), icon: 'none' })

      if (data.urlCode != '' && data.urlCode != null) {
        data.urlCode = ''
        // uni.navigateTo({
        // 	url:"/pages/barcodeManagement/finishedProductInventory"
        // })
        uni.navigateBack(1)  //返回到成品入库页面
      }

    } else {
      uni.showToast({ title: res.message, icon: 'none' })
    }
  })

}

//扫描纪录
const clickRight = () => {
  navigate({
    url: '/pages/barcodeManagement/finishedProductAdditionalRecord'
  })
}

//点击物理按键的返回
onBackPress((options) => {
  if (options.from == 'backbutton') {
    if (!data.barcodeList.length) {
      uni.navigateBack({
        delta: 1
      })
      return true
    }
    uni.showModal({
      title: t('smashRemoval.warmPrompt'),
      content: t('materials.unsubmittedDataIn'),
      success: function (res) {
        if (res.confirm) {
          //清除store 里面的数据
          store.commit('clearFinishedProductStorage')
          uni.navigateBack({
            delta: 1
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
    return true
  }
})

//导航栏左侧返回
const clickLeftBack = () => {
  navBackCheck()
}
const navBackCheck = () => {
  if (!data.barcodeList.length) {
    uni.navigateBack({
      delta: 1
    })
    return true
  }
  uni.showModal({
    title: t('smashRemoval.warmPrompt'),
    content: t('materials.unsubmittedDataIn'),
    success: function (res) {
      if (res.confirm) {
        store.commit('clearFinishedProductStorage') // 清空条码数据
        uni.navigateBack({
          delta: 1
        })
      } else if (res.cancel) {
        console.log('用户点击取消')
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.barcodeSplitting {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 88rpx);
  // height: 100vh;
}

.distributed-head {
  border-bottom-left-radius: 16rpx;
  border-bottom-right-radius: 16rpx;
}

.scroll {
  flex: 1;
  height: 2rpx;
}

.title {
  height: 2rpx;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    left: 50%;
    top: -8rpx;
    transform: translateX(-50%);
    width: 100%;
    height: 4rpx;
    background-color: #4CAF50; // 绿色小横线
  }
}

.title-with-text {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 20rpx 0;
  color: #666;
  font-size: 26rpx;
  position: relative;

  &::before,
  &::after {
    content: '';
    flex: 1;
    height: 2rpx;
    background-color: #e0e0e0;
  }

  &::before {
    margin-right: 20rpx;
  }

  &::after {
    margin-left: 20rpx;
  }
}

.continueInput {
  padding: 10rpx 10rpx;
  background-color: #4CAF50;
  color: white;
  border-radius: 10rpx;
  margin-left: 20rpx;
  font-size: 26rpx;
  text-align: center;
  min-width: 120rpx;
}

.continueInput:active {
  background-color: #45a049;
}
</style>
